package com.sise.wangzhan.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.protocol.RequestContent;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.cloud.netflix.zuul.util.ZuulRuntimeException;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;

/**
 * @Classname RestTemplateFilter
 * @Description TODO
 * @Date 2020/5/21 11:37
 * @Created by wangzhan
 */
public class RestTemplateFilter extends ZuulFilter {

    private RestTemplate restTemplate;

    public RestTemplateFilter(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Override
    public String filterType() {
        return FilterConstants.ROUTE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 2;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        // 获取请求URI
        String uri = request.getRequestURI();
        // 为不影响其他例子，uri含有exceptionTest才执行本过滤器
        if (uri.indexOf("exceptionTest") != -1){
            return true;
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        // 获取调用的服务的id
        String serviceId = String.valueOf(ctx.get("service-id"));
        // 获取请求的uri
        String uri = (String) ctx.get("requestURI");
        //组合成url给RestTemplate调用
        String url = "http://" + serviceId + uri;
        System.out.println("执行RestTemplateFilter, 调用的url：" + url);
        // 调用并获取结果
        String result = this.restTemplate.getForObject(url, String.class);
        // 设置路由状态，表示已经进行路由
        ctx.setResponseBody(result);
        // 设置响应标识
        ctx.sendZuulResponse();
        return null;
    }
}
